package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 定时处理超时订单任务
     */
    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void processTimeoutOrder() {
        log.info("自动处理超时订单： {}", LocalDateTime.now());

        // select * from order where status = 1 and create_time < now() - interval 15 minute
        List<Orders> pendingOrders = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if(pendingOrders != null && !pendingOrders.isEmpty()) {
            for (Orders order : pendingOrders) {
                // 处理超时订单逻辑
                order.setStatus(Orders.CANCELLED); // 设置订单状态为已取消
                order.setCancelReason("订单超时未支付，已自动取消"); // 设置取消原因
                order.setCancelTime(LocalDateTime.now()); // 设置取消时间
                orderMapper.update(order); // 更新订单状态
                log.info("订单号：{} 已超时取消", order.getNumber());
            }
        } else {
            log.info("没有超时订单需要处理");
        }
    }

    /**
     * 定时处理一直处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")  // 每天凌晨1点执行
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrders() {
        log.info("自动处理派送中订单： {}", LocalDateTime.now());

        // select * from order where status = 4
        List<Orders> pendingOrders = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if(pendingOrders != null && !pendingOrders.isEmpty()) {
            for (Orders order : pendingOrders) {
                // 处理派送中订单逻辑
                order.setStatus(Orders.COMPLETED); // 设置订单状态为已完成
                orderMapper.update(order); // 更新订单状态
                log.info("订单号：{} 已自动设置为已完成", order.getNumber());
            }
        } else {
            log.info("没有派送中订单需要处理");
        }
    }
}
